﻿using System;
using System.Collections.Generic;
using System.Linq;

namespace PeiYue.Common.Helper
{
    public class StringHelper
    {
        /// <summary>
        /// 根据分隔符返回前n条数据
        /// </summary>
        /// <param name="content">数据内容</param>
        /// <param name="separator">分隔符</param>
        /// <param name="top">前n条</param>
        /// <param name="isDesc">是否倒序（默认false）</param>
        /// <returns></returns>
        public static List<string> GetTopDataBySeparator(string content, string separator, int top, bool isDesc = false)
        {
            if (string.IsNullOrEmpty(content))
            {
                return new List<string>() { };
            }

            if (string.IsNullOrEmpty(separator))
            {
                throw new ArgumentException("message", nameof(separator));
            }

            var dataArray = content.Split(separator).Where(d => !string.IsNullOrEmpty(d)).ToArray();
            if (isDesc)
            {
                Array.Reverse(dataArray);
            }

            if (top > 0)
            {
                dataArray = dataArray.Take(top).ToArray();
            }

            return dataArray.ToList();
        }
        /// <summary>
        /// 将价格分转成字符串
        /// </summary>
        /// <param name="price"></param>
        /// <returns></returns>
        public static string formatPrice(int price)
        {
            return price / 100 + "." + (price % 100).ToString("d2");
        }
        /// <summary>
        /// 将金额转换为数值，转换单位为分
        /// </summary>
        /// <param name="text">待转换数值，单位为元</param>
        /// <returns></returns>
        public static int parsePrice(string text)
        {
            var price = text.ObjToDecimal();
            if (price <= 0) return 0;
            text += ".0";
            var arr = text.Split('.');
            var a = int.Parse(arr[0]) * 100;
            var t = arr[1] + "00";
            if (t.Length > 2)
            {
                t = t.Substring(0, 2);
            }
            var b = int.Parse(t);

            return a + b;
        }
        /// <summary>
        /// 清除字符串空格
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string RemoveSpace(string str)
        {
            return System.Text.RegularExpressions.Regex.Replace(str, @"\s", "");
        }

    }
}
